package com.hilon.foundation.main_child;


import com.hilon.foundation.para.QueryEntity;
import com.hilon.foundation.simple.BaseSimpleServiceImpl;
import com.hilon.foundation.util.HilonTools;
import com.hilon.foundation.util.ResultBean;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import jakarta.transaction.Transactional;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public abstract class BaseMainChildServiceImpl<T extends EntityBaseMain<C, VC>
        , C extends EntityBaseChild
        , V extends EntityBaseView<C, VC>, VC extends EntityBaseChild>
        extends BaseSimpleServiceImpl<T, V> {
    protected String childEntityName;
    protected String viewChildName;

    public BaseMainChildServiceImpl(EntityManager entityManager) {
        super(entityManager);
    }

    @Transactional
    public ResultBean<String> append(T entity) {
//        System.out.println(" BaseMainChild主子表中的append执行");
        String sql = "select count(e.id) as cnt " +
                "from " + entityName + " e " +
                "where e.no=?1 " +
                "and e.isDeleted = false ";
        try {
            Query query = entityManager.createQuery(sql);
//            System.out.println("entity.getNo的值是什么" + entity.getNo());
            query.setParameter(1, entity.getNo());
            Long e = (Long) query.getSingleResult();
            if (e == 0L) {
                entity.setTimeCreate(new Date());
                T curEntity = entityManager.merge(entity);
//                System.out.println(curEntity);
//                System.out.println("要增加的孩子父亲的ID是：" + curEntity.getId());
//                System.out.println("要增加的孩子对象是：" + entity.getChildren());
//                appendChildrenById(curEntity.getId(), entity.getChildren());
                Long id = curEntity.getId();
                for (C child : entity.getChildren()) {
                    child.setId(id);
                    entityManager.merge(child);
                }

//                appendOtherChildrenById(entity.getId(), entity);
                return new ResultBean<>(200, "成功增加记录");
            } else
                return new ResultBean<>(501, "增加记录失败-记录已经存在");

        } catch (DataAccessException e) {  // 明确捕获数据异常
            // 抛出非受检异常触发回滚
            throw new RuntimeException("数据库操作失败", e);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new ResultBean<>(501, "增加记录失败-数据库访问异常");
        }
    }

    @Transactional
    public ResultBean<String> edit(T entity) {
        System.out.println(" BaseMainChild主子表中的edit执行");
        System.out.println(entity);
        System.out.println("entityName: " + entityName);
        if (!entity.getPersonCheck().isEmpty())
            return new ResultBean<>(501, "保存记录失败-记录已经审核");
        String sql = "select e " +
                "from " + entityName + " e " +
                "where e.id=?1";
        try {
            Query query = entityManager.createQuery(sql);
            query.setParameter(1, entity.getId());
            T e = (T) query.getSingleResult();
            if (e != null) {
                entity.setTimeEdit(new Date());
                entityManager.merge(entity);
                editChildrenById(entity.getId(), entity.getChildren());
                editOtherChildrenById(entity.getId(), entity);
                return new ResultBean<>(200, "成功保存当前记录");
            } else
                return new ResultBean<>(501, "编辑记录失败-记录不存在");

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new ResultBean<>(501, "编辑记录失败-数据库访问异常");
        }
    }

    public void editOtherChildrenById(Long idPara, T entity) {
    }

    //等待需要的子类重写，默认是空函数

    public void appendOtherChildrenById(Long idPara, T entity) {
    }

    //等待需要的子类重写，默认是空函数

    public void deleteOtherChildrenById(Long idPara) {
    }

    //等待需要的子类重写，默认是空函数

    @Override
    @Transactional
    public ResultBean<String> deleteById(Long idPara) {
        deleteChildrenById(idPara);
        deleteOtherChildrenById(idPara);
        return super.deleteById(idPara);
    }

    public ResultBean<List<C>> getChildrenById(Long idPara) {
        String sql = "select e from " + childEntityName +
                " e where e.id=?1 ";
        try {
            Query query = entityManager.createQuery(sql);
            query.setParameter(1, idPara);
            List<C> list = (List<C>) query.getResultList();
            return new ResultBean<>(list);
        } catch (Exception e) {
            System.out.println(e);
            return new ResultBean<>(501, "getChildrenById执行错误");
        }
    }

    public ResultBean<List<VC>> getChildrenFullById(Long idPara) {
        String sql = "select e from " + viewChildName +
                " e where e.id=?1 ";
        try {
            Query query = entityManager.createQuery(sql);
            query.setParameter(1, idPara);
            List<VC> list = (List<VC>) query.getResultList();
            return new ResultBean<>(list);
        } catch (Exception e) {
            System.out.println(e);
            return new ResultBean<>(501, "getChildrenFullById执行错误");
        }
    }

    public List<VC> getChildrenFullByIdList(Long idPara) {
        String sql = "select e from " + viewChildName +
                " e where e.id=?1 ";
        try {
            Query query = entityManager.createQuery(sql);
            query.setParameter(1, idPara);
            List<VC> list = (List<VC>) query.getResultList();
            return list;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    public ResultBean<V> findById(Long idPara) {
        System.out.println("通过Id查找父表");
        V curEntity = super.findById(idPara).getResultData();
        if (curEntity.getId() != null) {
            System.out.println("再通过Id查找子表");
            List<VC> list = getChildrenFullByIdList(idPara);
            if (list.size() == 1 && list.get(0) == null) list = new ArrayList<>();
            System.out.println("返回的list大小是：" + list.size());
            System.out.println("返回的list是什么：" + list);
            curEntity.setChildrenView(list);
            return new ResultBean<>(curEntity);
        }
        return new ResultBean<>(501, "findById执行错误");
    }

    @Transactional
    public void appendChildrenById(Long id, List<C> children) {
        System.out.println("children里面的内容是什么" + children);
        try {
            for (C child : children) {
                child.setId(id);
                entityManager.merge(child);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @Transactional
    public void setIsDeletedChildById(Long idPara) {
        String sql = "update " + childEntityName +
                " e set e.isDeletedChild=true where e.id=?1 ";
        try {
            Query query = entityManager.createQuery(sql);
            query.setParameter(1, idPara);
            query.executeUpdate();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    @Transactional
    public void deleteAllIsDeletedChild() {
        String sql = "delete from " + childEntityName +
                " e where e.isDeletedChild = true";
        try {
            Query query = entityManager.createQuery(sql);
            query.executeUpdate();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    @Transactional
    public void editChildrenById(Long id, List<C> children) {
        try {
//            deleteChildrenById(id);
            setIsDeletedChildById(id);
            System.out.println("保存时带过来的孩子对象");
            System.out.println(children);
            for (C child : children) {
                child.setId(id);
                child.setIsDeletedChild(false);
                C curChild = entityManager.merge(child);
                System.out.println(curChild);
            }
            deleteAllIsDeletedChild();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @Transactional
    public void deleteChildrenById(Long id) {
        String sql = "delete from " + childEntityName +
                " e where e.id=?1 ";
        try {
            Query query = entityManager.createQuery(sql);
            query.setParameter(1, id);
            query.executeUpdate();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public ResultBean<List<V>> findAllMain() {
        String sql = "select e from " + viewName +
                " e " +
                "where not e.isDeleted " +
                "or e.isDeleted is null";
        try {
            Query query = entityManager.createQuery(sql);
            return new ResultBean<>((List<V>) query.getResultList());
        } catch (Exception e) {
            System.out.println(e);
            return new ResultBean<>(501, "findAllMain执行错误");
        }
    }


    @Transactional
    public ResultBean<String> check(T entity) {
        System.out.println("主子表中的check执行");
        String sql = "select e " +
                "from " + entityName + " e " +
                "where e.id=?1";
        try {
            Query query = entityManager.createQuery(sql);
            query.setParameter(1, entity.getId());
            T e = (T) query.getSingleResult();
            if (e != null) {
                entity.setTimeCheck(new Date());
                entityManager.merge(entity);
                editChildrenById(entity.getId(), entity.getChildren());
                return new ResultBean<>(200, "成功审核记录");
            } else
                return new ResultBean<>(501, "审核记录失败-记录不存在");

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new ResultBean<>(501, "审核记录失败-数据库访问异常");
        }
    }

    @Transactional
    public ResultBean<String> checkCancel(T entity) {
        System.out.println("BaseMainChildServiceImpl(简单表)中的checkCancel执行");
        String sql = "select e " +
                "from " + entityName + " e " +
                "where e.id=?1";
        try {
            Query query = entityManager.createQuery(sql);
            query.setParameter(1, entity.getId());
            T e = (T) query.getSingleResult();
            if (e != null) {
                entity.setPersonCheck("");
                entity.setTimeCheck(null);
                entityManager.merge(entity);


                return new ResultBean<>(200, "成功反审核记录");
            } else
                return new ResultBean<>(501, "反审核记录失败-记录不存在");

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new ResultBean<>(501, "反审核记录失败-数据库访问异常");
        }
    }

    @Transactional
    public ResultBean<C> saveChild(C child) {
        try {
            child.setIsDeletedChild(false);
            C curChild = entityManager.merge(child);
            return new ResultBean<>(curChild);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new ResultBean<>(501, "保存本行子记录失败-数据库访问异常");
        }
    }

    @Transactional
    public ResultBean<List<V>> getQueryData(String categoryType, String entityName,
                                            String categoryName, String categoryTypeDetail,
                                            QueryEntity queryEntity) {
        System.out.println("后端中的categoryType的值是什么: " + categoryType);
        System.out.println("后端中的entityName的值是什么: " + entityName);
        System.out.println("后端中的categoryName的值是什么: " + categoryName);
        System.out.println("后端中的categoryTypeDetail的值是什么: " + categoryTypeDetail);
        String sql;
        List<V> resultList = null;
        try {
            switch (entityName) {
                case "OpenPerform" -> {
                    sql = " select e from  " + viewName + " e  where " +
                            "e.categoryName = :categoryNames " +
                            "and e.categoryType = :categoryTypes " +
                            "and e.categoryTypeDetail = :categoryTypeDetails " +
                            "and ( ";

                    // 将动态查询条件添加到原始 SQL 查询中
                    sql += " e.batchNo like :str1 or e.batchNoPerform like :str1 or e.specificationPerform like :str1 or " +
                            " e.manufacturer like :str1 or e.steelGrade like :str1 or e.specification like :str1 or " +
                            " e.contractNo like :str1 or e.batchNoOriginal like :str1 or e.customer like :str1 or " +
                            " e.noOpenPlan like :str1 or e.unit like :str1 or e.shift like :str1 or e.no like :str1 or " +
                            " e.personCreate like :str1 or e.personEdit like :str1 or e.personCheck like :str1 or " +
                            " e.qualityConclusion like :str1 )" +
                            "  and (e.timeCreate between :dateBegin1 and :dateEnd1 or e.timeCheck between :dateBegin1 and :dateEnd1 " +
                            "  or e.timeEdit between :dateBegin1 and :dateEnd1 ) ";

                    if (queryEntity.getStr4().equals("全部")) {
                        System.out.println("查询全部 sql不变");
                    } else if (queryEntity.getStr4().equals("已审核")) {
                        // 构建SQL查询的基本部分  已审核和复核完成
                        sql += " and (e.personCheck != '' and e.isDeleted = 0) ";
                    } else {
                        // 构建SQL查询的基本部分
                        sql += " and (e.personCheck = '' and e.isDeleted = 0) ";
                    }
                    sql += " ORDER BY e.timeCreate DESC ";

                    try {
                        // sql的参数必须和setParameter一一对应，数量不同会报错
                        System.out.println("sql语句我想看看：" + sql);
                        if (categoryName.equals("全部")) categoryName = "";
                        if (categoryTypeDetail.equals("全部")) categoryTypeDetail = "";
                        Query query = entityManager.createQuery(sql);
                        query.setParameter("categoryTypes", categoryType);// 表类型
                        query.setParameter("categoryNames", categoryName);// 表类型
                        query.setParameter("categoryTypeDetails", categoryTypeDetail);// 表类型*/
                        query.setParameter("str1", queryEntity.getStr1().isEmpty() ? "%"
                                : "%" + queryEntity.getStr1() + "%");// --3即Str1特殊，通查所有str字段--查询条件str-----均使用like做查询处理
                        query.setParameter("dateBegin1", queryEntity.getDateBegin1());//查询条件
                        query.setParameter("dateEnd1", queryEntity.getDateEnd1());//查询条件
                        resultList = (List<V>) query.getResultList();

                    } catch (Exception e) {

                        return null;
                    }
                }
            }
            return new ResultBean<>(resultList);
        } catch (Exception e) {
            return new ResultBean<>(500, "getQueryData执行错误" + e.getMessage());
        }

    }

    @Transactional
    public ResultBean<String> deleteByIds(List<Long> ids) {
        String idsStr = HilonTools.getIdsStr(ids);
        System.out.println("删除的时候没有执行吗");
        String sqlChild = "update " +
                childEntityName +
                " e set e.isDeletedChild=true " +
                "where e.id in (" + idsStr + ") ";

        String sql = "update " +
                entityName +
                " e set e.isDeleted=true " +
                "where e.id in (" + idsStr + ") ";
        ;
        try {
            Query queryChild = entityManager.createQuery(sqlChild);
            int j = queryChild.executeUpdate();
            Query query = entityManager.createQuery(sql);
            int i = query.executeUpdate();
            if (i > 0 && j >= 0)
                return new ResultBean<>(200, "删除成功");
            else
                return new ResultBean<>(501, "删除失败,数据库操作存在问题");
        } catch (Exception e) {
            System.out.println(e);
            return new ResultBean<>(501, "删除程序失败");
        }
    }


}
